#include "bitencoder.h"

namespace WingGif {

BitEncoder::BitEncoder(int initBit, QObject *parent) : QObject(parent) {
  inBit = initBit;
}

int BitEncoder::length() { return outList.length(); }

void BitEncoder::add(int inByte) {
  // Shifts the input value to the bit position (0 to 8).
  // Merges the current value with the shifted input value.
  // They will never colide, 00000100 | 00000101 = 00101100 (4 | 5 = 44)
  _currentVal |= (inByte << (_currentBit));

  _currentBit += inBit;

  // The output always use 8 bits, even if the codesize ranges from 3-12 bits.
  // So, it needs 3+3+3bits to output 1 byte (1 bit will be left to the next
  // byte).
  while (_currentBit >= 8) {
    auto outVal = char(_currentVal & 0XFF);
    _currentVal =
        _currentVal >> 8; //"Eats" the first eight positions to the right.
    _currentBit -= 8;

    outList.append(outVal);
  }
}

void BitEncoder::end() {
  // Should output the value even if does not fill 8 bits.
  while (_currentBit > 0) {
    auto outVal = char(_currentVal & 0XFF);
    _currentVal = _currentVal >> 8;
    _currentBit -= 8;

    outList.append(outVal);
  }
}

} // namespace WingGif
